var app = angular.module("listApp", []),
    parid = UI.getParameterByName('parId');
var tay_time = UI.getTimes().times();

var timeout_json = function(data, $window) {
    if(data.returnCode == 999994) {
        var ss = 3;
        layer.msg(data.returnMessage + "！<strong class='Ajax_Out'>" + ss + "</strong> 秒后前往登录页", 50, -1);
        var picInt = setInterval(function() {
            if(ss >= 1) {
                ss = ss - 1;
                $('.Ajax_Out').text(ss);
            } else {
                clearInterval(picInt);
                try {
                    $window.parent.location.href = data.returnData;
                    $window.location.href = data.returnData;
                } catch(e) {
                    log('timeout!')
                }
            }
        }, 1000);
        return false;
    }
}

app.config(function($httpProvider) {
    $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
});

app.controller('tableCtrl', function($scope, $http, $window) {
    var vm = $scope.vm = {
        pageIndex: 1,
        pageSize: 10,
        ifm_name: '',
        ifm_note: '',
        ifm_categoryName: '',
        groupId:'',
        ifm_isdelete:''
    }
    var stpage = function(ii) {
        var jpage = [],
            index = vm.pageIndex,
            pcount = vm.pageSize,
            total = $scope.datas.totalRecords;
        len = 0,
            j = 0,
            pindex,
            tii = (ii - 1) / 2,
            sii = (ii - 1);
        if(total % pcount == 0) {
            len = total / pcount;
        } else {
            len = parseInt(total / pcount) + 1;
        }
        if(len >= ii) {
            if(index < ii) {
                for(var i = 1; i <= len; i++) {
                    j++;
                    if(j <= ii) jpage.push(i);
                }
            } else if(index >= len - sii) {
                var pindex = index < len - tii ? index - tii : len - sii;
                for(var i = pindex; i <= len; i++) {
                    j++;
                    if(j <= ii) jpage.push(i);
                }
            } else {
                for(var i = index - tii; i <= len; i++) {
                    j++;
                    if(j <= ii) jpage.push(i);
                }
            }
        } else {
            for(var i = 1; i <= len; i++) {
                jpage.push(i);
            }
        };
        $scope.pages_e = len;
        $scope.pages = jpage;
    }
    $scope.domAjax = function(e, id, name) {
        if((e === 'del') || (e === 'delAll')) {
        	$http.get(basePath + 'iformation/selectModel.do?ifm_id=' + id).success(function(data){
        		if(data.returnData >0){
            		$.layer({
                        title: "温馨提示：",
                        shade: [0],
                        area: ['auto','auto'],
                        dialog: {
                            msg: data.returnMessage,
                            btns: 2,
                            type: -1,
                            btn: ['确定', '取消'],
                            yes: function() {
                            	window.parent.location.href = basePath + "report/reportTemplateList.jsp?parId=301";
                            },
                            no: function() {}
                        }
                    });
        		}else{
            		$.layer({
                        title: "温馨提示：",
                        shade: [0],
                        area: ['230','auto'],
                        dialog: {
                            msg: "确定删除吗？",
                            btns: 2,
                            type: -1,
                            btn: ['确定', '取消'],
                            yes: function() {
                                $http.get(basePath + 'iformation/deleteIformation.do?ifm_id=' + id + '&ifm_name=' + name).success(function(data) {
                                    var j = timeout_json(data, $window);
                                    if(j == false) {
                                        return false;
                                    }
                                    layer.msg(data.returnMessage, 1, -1);
        							setTimeout(function() {
        								if(window.reLength==1&&vm['pageIndex']>1){
        									$scope.setAjax({"pageindex" : vm['pageIndex']-1});
        								}else{
        									$scope.setAjax();
        								}
        							},1000);
                                });
                            },
                            no: function() {}
                        }
                    });
        		}

        	});
        }
    }
    $scope.modifyBtn = function(id,groupIde) {
    	if(id != undefined) {
    		$http.get(basePath + 'iformation/queryByID2.do?ifm_id=' + id + '&groupId=' + (groupIde||"")).success(function(data) {
    			var j = timeout_json(data, $window);
    			if(j == false) {
    				return false;
    			}
    			if(data.returnCode == 10000) {
    				content = $scope.content = data.returnData;
    		        var getChannel = content.ifm_getChannel,
    		        	notChannel = content.ifm_notChannel,
    		        	getWechatId = content.ifm_getWechatId,
    		        	notWechatId = content.ifm_notWechatId,
    		        	getBloggerId = content.ifm_getBloggerId,
    		        	notBloggerId = content.ifm_notBloggerId,
    		        	getBbsName = content.ifm_getBbsName,
    		        	notBbsName = content.ifm_notBbsName,
    		        	getKeyword = content.ifm_getKeyword,
    		        	notKeyword = content.ifm_notKeyword;
    		        //以下判断，经需求确认后，暂时取消。
/*    		        if( getChannel!='None' || notChannel!='None' ||
    		        getWechatId!='None' || notWechatId!='None' || 
    		        getBloggerId!='None' || notBloggerId!='None' ||
    		        getBbsName!='None' || notBbsName!='None' ||
    		        getKeyword!='None' || notKeyword!='None'){*/
        				$.layer({
        		            title: "温馨提示：",
        		            shade: [0],
        		            area: ['230', 'auto'],
        		            dialog: {
        		                msg: '确定'+($scope.content.ifm_isdelete==0?"开启方案吗？":"关闭方案吗？"),
//        		                msg: '确定要修改为'+($(this)[0].$$watchers[0].last)+"状态?",
        		                btns: 2,
        		                type: -1,
        		                btn: ['确定', '取消'],
        		                yes: function() {
        		        			var params = {
        		    					ifm_id: content.ifm_id,
        		    					ifm_name: content.ifm_name,
        		    					ifm_pushed: content.ifm_pushed,
        		    					ifm_type: content.ifm_type,
        		    					ifm_note: content.ifm_note,
        		    					ifm_categoryName: content.ifm_categoryName,
        		    					ifm_getChannel: getChannel,
        		    					ifm_notChannel: notChannel,
        		    					ifm_getWechatId: getWechatId,
        		    					ifm_notWechatId: notWechatId,
        		    					ifm_getBloggerId: getBloggerId,
        		    					ifm_notBloggerId: notBloggerId,
        		    					ifm_getBbsName: getBbsName,
        		    					ifm_notBbsName: notBbsName,
        		    					ifm_getKeyword: getKeyword,
        		    					ifm_notKeyword: notKeyword,
        		    					ifm_isdelete: content.ifm_isdelete,
        		    					ifm_matePattern: content.ifm_matePattern,
        		    					ifm_filterPattern: content.ifm_filterPattern
        		    				};
        		        			//0--表示目前为关闭状态，点击按钮后请求开启，所以赋值为1，再发送。
        		        			if(params.ifm_isdelete==0){
        		        				params.ifm_isdelete=1;
        		        			}else{
        		        				params.ifm_isdelete=0;
        		        			}
        		                    $.post(basePath + 'iformation/modifyIformation.do?discern=3', params).success(function(data) {
        		                        var j = timeout_json(data, $window);
        		                        if(j == false) {
        		                            return false;
        		                        }
        		            			layer.msg(data.returnMessage, 1, 10);
        		                        setTimeout(function() {
        		                            $scope.setAjax();
        		                        },800);
        		                    });
        		                },
        		                no: function() {}
        		            }
        		        });
/*    		        }else{
    		        	$.layer({
        		            title: "操作失败原因：",
        		            shade: [0],
        		            area: ['430', 'auto'],
        		            dialog: {
        		                msg: '“资源编辑”或“关键词编辑”中，请至少选择一项进行操作!',
        		                btns: 1,
        		                type: -1,
        		                btn: ['确定'],
        		                yes: function() {
        		                	layer.closeAll('dialog');
        		                },
        		                no: function(){
        		                	alert(222);
        		                }
        		            }
    		        	});
    		        }*/
    			}
    		});
    	} 
    }
    $scope.setAjax = function(obj) {
        if(obj) {
            vm["pageSize"] = obj.pagesize || vm["pageSize"];
            vm["pageIndex"] = obj.pageindex || vm["pageIndex"];
			//判断输入的页数是否大于最大的页数
			if(vm["pageIndex"]>$scope.pages_e){
				vm["pageIndex"]=$scope.pages_e;
			}
        }
        $scope.addparid = parid;
        vm.ifm_isdelete = $("#ifm_isdelete").val();
        url = basePath + 'iformation/queryByParams.do?pageIndex=' + vm['pageIndex'] + '&pageSize=' + vm['pageSize'] +  '&vtimes=' + new Date().getTime();
        if(vm.ifm_name != undefined && vm.ifm_name != "") url = url + '&ifm_name=' + encodeURIComponent(vm['ifm_name']);
        if(vm.ifm_note != undefined && vm.ifm_note != "") url = url + '&ifm_note=' + encodeURIComponent(vm['ifm_note']);
        if(vm.ifm_categoryName != undefined && vm.ifm_categoryName != "") url = url + '&ifm_categoryName=' + encodeURIComponent(vm['ifm_categoryName']);
        if(vm.groupId != undefined && vm.groupId !="") url = url + '&groupId=' + vm["groupId"];
        if(vm.ifm_isdelete != undefined && vm.ifm_isdelete != "") url = url + "&ifm_isdelete=" + vm['ifm_isdelete'];
        
	    var dLoading='';
	    $scope.dLoading=true;
	    $(".fuzzy").addClass("fuzzyCss");
        
        $http.get(url).success(function(data) {
			//获取本次返回数据的条数
			window.reLength = data.returnData.length;
			//取得当前页面的上一页、下一页
			$scope.prevIndex = parseInt($("#jsgo .cur").text())-1;
			$scope.nextIndex = parseInt($("#jsgo .cur").text())+1;
			
            var j = timeout_json(data, $window);
            if(j == false) {
                return false;
            }
            $('#zcont').removeClass('checked');
            $scope.datas = data;
            stpage(7);
			$scope.dLoading=false;
			$(".fuzzy").removeClass("fuzzyCss");
			if($scope.dLoading==false){
				if(data.returnData.length <= 0) {
					layer.msg('无数据！', 1, -1);
				}
			}
            $scope.keyInt="";
        });
    };
    $scope.setAjax();

    $scope.getAjax = function() {
        vm["pageIndex"] = 1;
        $scope.setAjax();
    }

    $(document).live('keyup', function(e) {
        e = e || window.event;
        if(e.keyCode == 13) {
            $scope.getAjax();
        }
    })
});

app.directive('pagen', function() { //页总数
    return {
        link: function($scope, ele) {
            ele.bind('click', function() {
                var pagesize = $(this).text();
                $(ele).addClass('cur').siblings().removeClass('cur');
                $scope.setAjax({
                    "pagesize": pagesize,
                    "pageindex": 1
                })
            })

        }
    }
});
app.directive('pageg', function() { //fenye
    return {
        link: function($scope, ele) {
            ele.bind('click', function() {
                var index = $(this).attr('data-href');
				/**
				 * 条件一：如果index为非数字，点击上一页，设为当前页码-1;
				 * 条件二：如果index为非数字，点击下一页，设为当前页码+1;
				 */
				if(isNaN(index) && $(this).attr('class')=="str"){
					index = parseInt($("#jsgo .cur").text())-1;
				}else if(isNaN(index) && $(this).attr('class')=="end"){
					index = parseInt($("#jsgo .cur").text())+1;
				}
                $scope.setAjax({
                    "pageindex": index
                })
            })
        }
    }
});
app.directive('agSelect', function($http){
	return { 
		restrict:'AE',
		scope:{ 
			groupId:'=groupId'
		},
		template:'<div class="ui_select"><input type="text" id="groupInputText" class="ui_s_t" ng-bind="stxt" ng-model="stxt" /><div class="ui_s_bk"><a href="javascript:void(0)" class="cur" data-id="0">全部</a><a href="javascript:void(0)" ng-repeat="key in dataGroupSelects | filter: {groupName:stxt} " ng-bind="key.groupName" data-id="{{key.groupId}}"></a></div></div>',
		controller:function($scope,$element,$attrs){ 
			var a = $element.find('.ui_s_t'),
				b = $element.find('.ui_s_bk'),
				c = $attrs.ajaxs,
				d = $attrs.loadajaxs;
			$element.children('.ui_select').css('zIndex',100);
			$element.bind('click', function() {
				b.slideDown();
			});
			$element.bind('mouseleave', function() {
				if(a.text()!=""){
					b.hide();
				}
			});

		},
		link:function($scope,$element,$attrs){ 
			$scope.stxt='全部';
			var a=$element.find('.ui_s_t'),
				b=$element.find('.ui_s_bk'),
				c=$attrs.ajaxs;
			
			if(c!=undefined)
			{
				$http.get(c+'?vtimes='+new Date().getTime()).success(function(data){ 
					$scope.dataGroupSelects=data.returnData;
				});
			}			
			a.click(function() {
				$scope.stxt=undefined;
				$scope.$apply();
			});
			b.find('a').live("click",function(){ 
				b.hide();
				$(this).addClass('cur').siblings().removeClass('cur');
				a.val($(this).text());
				$scope.stxt=$(this).text();
				if($attrs.groupId!=undefined) {
					$scope.groupId=parseInt($(this).attr('data-id')); 
					$("#groupIds").val(parseInt($(this).attr('data-id')));
				}
				$scope.$apply();
 				return false;
			});
			$element.bind('mouseleave',function(){ 
				$("#groupInputText").val(b.find('a.cur').text());
				b.find('.ui_s_t').blur();
				b.hide();
//				$scope.$apply();
				return false;
			});
		}
	}
});

$(function() {
    UI.message().base();
    laydate.skin('molv');

//  $('#setPlatform,#setPlatform_div').hover(function() {
//      $('#setPlatform_div').toggle();
//  })

    $('#zcont').on('click', function() {
        $(this).toggleClass('checked');
        if($(this).attr('class').search('checked') > -1) {
            $('.td .ui_checkbox').addClass('checked');
        } else {
            $('.td .ui_checkbox').removeClass('checked');
        }
    });
    $('.td .ui_checkbox').live('click', function() {
        $(this).toggleClass('checked');
    });
    $('.tips').live('mouseenter', function() {
        layer.tips($(this).attr('data-tips'), this, {
            style: ['background-color:#fff; color:#666;padding:10px; font-size:13px;line-height:24px;', '#fff'],
            guide: 2,
            time: 1
        });
    });
    $('.tips').live('mouseleave', function() {
        $('.xubox_tips').remove()
    })

	$('.ui_select_msg').each(function() {
		var _ = $(this),
			_a = _.find('.ui_s_t_msg'),
			_c = _.find('.ui_s_bk_msg'),
			_ca = _c.find('a');
		_a.live('click', function() {
			_c.slideToggle(200, "easeInSine");
		});
		_ca.live('click', function() {
			$(this).addClass('cur').siblings().removeClass('cur');
			_a.text($(this).text());
			$("#ifm_isdelete").val($(this).attr("type"));
			_c.slideToggle(200, "easeInSine");
		});
		_c.live('mouseleave', function() {
			_c.stop(false, true).slideUp(200, "easeInSine");
		});
	});

	$('.ui_select_msg').live('keyup', function(e) {
		var _ = $(this),
			b = _.find('.ui_s_bk_msg'),
			di = 27;
		_.focus();
		e = e || window.event;
		var indx = b.find('a.cur').index() || 0;
		if(e.keyCode == 40) {
			var aindx = indx + 1,
				sct;
			if(rindx >= b.find('a').length) {
				rindx = b.find('a').length;
			}
			b.find('a').eq(aindx).addClass('cur').siblings('a').removeClass('cur');
			sct = aindx * di > 180 ? aindx * di - 80 : 0;
			b.scrollTop(sct);
		} else if(e.keyCode == 38) {
			var rindx = indx - 1,
				sct;
			sct = aindx * di > 100 ? aindx * di : 0;
			if(rindx <= 0) {
				rindx = 0;
			}
			b.find('a').eq(rindx).addClass('cur').siblings('a').removeClass('cur');
			sct = rindx * di > 180 ? rindx * di - 80 : 0;
			b.scrollTop(sct);
		} else if(e.keyCode == 13) {
			b.find('a.cur').trigger('click');
			_.blur();
			_.find('.ui_s_t_msg').blur();
		}
		return false;
	});
});